/*
 * @lc app=leetcode.cn id=2226 lang=typescript
 *
 * [2226] 每个小孩最多能分到多少糖果
 */

// @lc code=start
function maximumCandies(candies: number[], k: number): number {
  // 当前糖果可以分的堆数
  const isCheck = (k: number): number => {
    if (k === 0) return Number.MAX_SAFE_INTEGER;
    let res = 0;
    for (const x of candies) {
      res += Math.floor(x / k);
    }
    return res;
  };
  let l = 0;
  let r = Math.max(...candies) + 1;
  let mid: number;
  while (l < r) {
    mid = l + Math.floor((r - l) / 2);
    if (isCheck(mid) >= k) l = mid + 1;
    else r = mid;
  }
  return l - 1;
}
// @lc code=end
